<script setup lang="ts">
import { onMounted, reactive, Ref, ref, nextTick } from 'vue'
import SysDialog from '@/components/dialog/SysDialog.vue'

import { ElMessage, FormInstance } from 'element-plus'
import {
  addApi,
  getListApi,
  editApi,
  deleteApi,
  getRoleDataScope,
} from '@/api/role/index.ts'
import { SysRole } from '@/api/role/type.ts'
import AssignTree from '@/views/system/role/AssignTree.vue'
import useDialog from '@/hooks/useDialog.ts'
// 弹框属性
const { dialog, onShow, onClose, onConfirm } = useDialog()
import useInstance from '@/hooks/useInstance.ts'
import DataScope from "@/views/system/role/DataScope.vue";
// 获取全局 global
const { global } = useInstance()

// 菜单树的ref属性
const assignTree = ref()

// 总条数
const total: Ref<number> = ref(0)

// 搜索表单绑定对象
const searchParam = reactive({
  roleName: '',
  page: 1,
  limit: 10,
})

// 表单ref属性
const addRef = ref<FormInstance>()

// 新增表单绑定对象
const addModel = reactive(<SysRole>{
  id: undefined,
  roleName: '',
  code: '',
})

// 表单校验规则
const rules = reactive({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
})

// 表格高度
const tableHeight = ref()
// 表格数据
const tableData = ref([])

// 新增按钮
const addBtn = () => {
  dialog.title = '新增角色'
  dialog.height = 180
  dialog.width = 480
  // 清理表单
  addRef.value?.resetFields()
  // 清空值
  Object.assign(addModel, {
    id: null,
    roleName: '',
    code: '',
  })
  // 显示弹框
  onShow()
}

// 搜索按钮
const searchBtn = () => {
  searchParam.page = 1
  getList()
}

// 重置按钮
const resetBtn = () => {
  searchParam.roleName = ''
  searchParam.page = 1
  getList()
}

// 表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('通过')
      try {
        // 提交请求
        if (addModel.id == null) {
          const result = await addApi(addModel)
          ElMessage.success('新增角色成功')
        } else {
          const result = await editApi(addModel)
          ElMessage.success('修改角色成功')
        }
        // 刷新列表
        getList()
        // 关闭弹框
        onClose()
      } catch (error) {}
    }
  })
}

//列表查询
const getList = async () => {
  try {
    let res = await getListApi(searchParam)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {}
}

// 编辑按钮
const editBtn = (row: SysRole) => {
  // 显示弹框
  dialog.title = '编辑角色'
  dialog.height = 180
  onShow()
  // 清理表单
  addRef.value?.resetFields()
  // 回显数据
  Object.assign(addModel, {
    id: row.id,
    roleName: row.roleName,
    code: row.code,
  })
}

// 分配菜单按钮
const assignBtn = (row: SysRole) => {
  assignTree.value.show(row)
}

// 数据权限组件ref
const dataScopeRef = ref()

// 数据权限按钮点击事件
const handleDataScope = (row: SysRole) => {
  dataScopeRef.value.show(row.id)
}

// 删除按钮
const deleteBtn = async (roleId: number) => {
  const confirm = await global.$myConfirm('此操作将永久删除该角色，是否继续?')
  if (confirm) {
    try {
      const result = await deleteApi(roleId)
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    } catch (error) {}
  }
}

onMounted(() => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 240
  })
  // 查询角色列表
  getList()
})
</script>

<template>
  <!--el-min是布局日期-->
  <el-main>

    <el-card shadow="never" style="height: 75px;">
      <!--搜索栏-->
      <el-form :model="searchParam"
               ref="form"
               :inline="true">
        <el-form-item label="角色名称">
          <el-input style="width: 220px"
                    v-model="searchParam.roleName"
                    placeholder="请输入角色名称关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="Search"
                     @click="searchBtn">搜索</el-button>
          <el-button icon="Close"
                     type="danger"
                     plain
                     @click="resetBtn">重置</el-button>
          <el-button icon="Plus"
                     type="primary"
                     @click="addBtn"
                     v-permission="['sys:role:add']">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--表格数据-->
    <el-table :height="tableHeight"
              :data="tableData"
              style="width: 100%;margin-top: 15px"
              stripe
              border>
      <el-table-column type="index"
                       label="#"
                       width="50" />
      <el-table-column prop="roleName"
                       label="角色名称" />
      <el-table-column prop="code"
                       label="角色编码" />
      <el-table-column label="操作"
                       width="320"
                       align="center">
        <template #default="scope">
          <el-button link
                     type="primary"
                     size="small"
                     icon="edit"
                     @click.prevent="editBtn(scope.row)"
                     v-permission="['sys:role:update']">编辑</el-button>
          <el-button link
                     type="success"
                     size="small"
                     icon="edit"
                     @click.prevent="assignBtn(scope.row)"
                     v-permission="['sys:role:assign']">分配菜单</el-button>
          <el-button link
                     type="warning"
                     size="small"
                     icon="setting"
                     @click.prevent="handleDataScope(scope.row)">数据权限</el-button>
          <el-button link
                     type="danger"
                     size="small"
                     icon="delete"
                     @click.prevent="deleteBtn(scope.row.id)"
                     v-permission="['sys:role:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页器-->
    <div class="pagination">
      <el-pagination v-model:current-page="searchParam.page"
                     v-model:page-size="searchParam.limit"
                     :page-sizes="[10, 15, 20, 30]"
                     :background="true"
                     layout='prev, pager, next, jumper,->,sizes,total'
                     :total="total"
                     @size-change="getList"
                     @current-change="getList" />
    </div>

    <!--新增、编辑-->
    <SysDialog :title="dialog.title"
               :width="dialog.width"
               :height="dialog.height"
               :visible="dialog.visible"
               @on-close="onClose"
               @on-confirm="commit">
      <template v-slot:content>
        <el-form :model="addModel"
                 ref="addRef"
                 :rules="rules"
                 label-width="80px">
          <el-form-item label="角色名称"
                        prop="roleName">
            <el-input v-model="addModel.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色编号"
                        prop="code">
            <el-input v-model="addModel.code"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </SysDialog>
    <!--分配菜单-->
    <AssignTree ref="assignTree"></AssignTree>
    <!-- 添加数据权限组件 -->
    <DataScope ref="dataScopeRef" />
  </el-main>
</template>


<style scoped>
.pagination {
  margin-top: 20px;
}
</style>
